﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

using ClientLib;

namespace JigsawAdmin.SubForms.Security
{
    public partial class Groups : Form
    {
        TreeNode _selectednode;
        ClientUtil _cutil;
        JsvcEnc.EncSoapXml xmlsvc;

        public Groups(ClientUtil cUtil)
        {
            InitializeComponent();

            _cutil = cUtil;
            xmlsvc = new JsvcEnc.EncSoapXml();
            xmlsvc.Url = _cutil.ServiceURL;

            // set up folder images for treeview
            ImageList apiTreeList = new ImageList();
            apiTreeList.Images.Add(Image.FromFile("../../Images/Folder.png"));
            apiTreeList.Images.Add(Image.FromFile("../../Images/Node.png"));
            apiTreeList.Images.Add(Image.FromFile("../../Images/Rootfolder.png"));

            trvGroups.ImageList = apiTreeList;
            trvGroups.ImageIndex = 0;
            trvGroups.SelectedImageIndex = 1;
        }

        /// <summary>
        /// 
        /// </summary>
        private void Groups_Shown(object sender, EventArgs e)
        {
            try
            {
                PopulateGroupTree();
            }
            catch (Exception ex)
            {
                ErrorUtil eutil = new ErrorUtil();
                eutil.LogException(_cutil.UserID, "Groups Groups_Shown", "", ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private bool ValidateData()
        {
            bool isValid = true;

            if (txtGroupName.Text == "") isValid = false;
            if (txtDescription.Text == "") isValid = false;

            return isValid;
        }


        /// <summary>
        /// 
        /// </summary>
        private void TreeEvents()
        {
            switch (_selectednode.Level)
            {
                case 0:
                    // root node level - do nothing
                    break;

                case 1:
                    // role level, get role versions
                    PopulateGroupVersions();

                    break;

                case 2:
                    // not used - do nothing
                    break;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        public void PopulateGroupTree()
        {
            // populate the top level of the tree
            Dictionary<string, string> paramList = new Dictionary<string, string>();

            string encryptedinput = _cutil.BuildMessageXML("SystemAdmin.GetAllGroups.Base", paramList, true);
            string results = xmlsvc.Controller(_cutil.EncSymmKey, encryptedinput);

            EncryptUtil eutil = new EncryptUtil();
            _cutil.ParseResponseMessage(eutil.DecryptString2(results, _cutil.SymmKey));

            if (_cutil.ResponseCode == "Success")
            {
                string tmpdata = _cutil.Result;
                tmpdata = tmpdata.Replace("<![CDATA[", "");
                tmpdata = tmpdata.Replace("]]>", "");

                StringReader sr = new StringReader(tmpdata);
                DataTable grouplist = new DataTable();
                grouplist.ReadXml(sr);

                if (grouplist.Rows.Count > 0)
                {
                    trvGroups.BeginUpdate();
                    trvGroups.Nodes.Clear();

                    // populate root node of API tree
                    GroupTreeNode gtnr = new GroupTreeNode();
                    gtnr.GroupName = "Jigsaw Roles";

                    TreeNode tnr = new TreeNode();
                    tnr.Text = "Jigsaw Groups";
                    tnr.ImageIndex = 2;
                    tnr.SelectedImageIndex = 2;
                    tnr.Tag = gtnr;

                    trvGroups.Nodes.Add(tnr);

                    // populate top level of API tree
                    foreach (DataRow dr in grouplist.Rows)
                    {
                        GroupTreeNode gtn = new GroupTreeNode();
                        gtn.GroupName = dr["GroupName"].ToString();
                        gtn.GID = dr["GlobalID"].ToString();

                        TreeNode tn = new TreeNode();
                        tn.Text = dr["GroupName"].ToString();
                        tn.ImageIndex = 1;
                        tn.SelectedImageIndex = 1;
                        tn.Tag = gtn;

                        tnr.Nodes.Add(tn);
                    }

                    trvGroups.EndUpdate();
                }
            }
        }


        /// <summary>
        /// 
        /// </summary>
        public void PopulateGroupVersions()
        {
            // get info from the selected tree node and tag object
            GroupTreeNode selectedTag = (GroupTreeNode)_selectednode.Tag;
            lblSelectedGroup.Text = "Selected Group: " + selectedTag.GroupName;
            Dictionary<string, string> paramList = new Dictionary<string, string>();
            paramList.Add("GroupID", selectedTag.GID);

            string encryptedinput = _cutil.BuildMessageXML("SystemAdmin.GetGroupVersions.Base", paramList, true);
            string results = xmlsvc.Controller(_cutil.EncSymmKey, encryptedinput);

            EncryptUtil eutil = new EncryptUtil();
            _cutil.ParseResponseMessage(eutil.DecryptString2(results, _cutil.SymmKey));

            if (_cutil.ResponseCode == "Success")
            {
                string tmpdata = _cutil.Result;
                tmpdata = tmpdata.Replace("<![CDATA[", "");
                tmpdata = tmpdata.Replace("]]>", "");

                StringReader sr = new StringReader(tmpdata);
                DataTable verlist = new DataTable();
                verlist.ReadXml(sr);

                if (verlist.Rows.Count > 0)
                {
                    dgvGroupVersions.DataSource = verlist;
                    PopulateGroupForm();
                }
                else
                {
                    dgvGroupVersions.DataSource = null;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void PopulateGroupForm()
        {
            txtGlobalID.Text = dgvGroupVersions.SelectedRows[0].Cells["GlobalID"].Value.ToString();
            txtGroupName.Text = dgvGroupVersions.SelectedRows[0].Cells["GroupName"].Value.ToString();
            txtDescription.Text = dgvGroupVersions.SelectedRows[0].Cells["Description"].Value.ToString();

            

            btnSave.Enabled = true;
            btnDelete.Enabled = true;
            string rowstate = dgvGroupVersions.SelectedRows[0].Cells["RowState"].Value.ToString();
            if (rowstate != "Active")
            {
                btnRollback.Enabled = true;
                btnDelete.Enabled = false;
            }
            else
            {
                btnRollback.Enabled = false;
                btnDelete.Enabled = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void ClearGroupForm()
        {
            dgvGroupVersions.DataSource = null;
            txtGlobalID.Text = "";
            txtGroupName.Text = "";
            txtDescription.Text = "";
            dgvGroupRoles.DataSource = null;

            btnSave.Enabled = false;
            btnDelete.Enabled = false;
            btnRollback.Enabled = false;
        }

        /// <summary>
        /// 
        /// </summary>
        private void trvGroups_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                ClearGroupForm();

                // assign the selected node
                _selectednode = trvGroups.SelectedNode;

                TreeEvents();
            }
            catch (Exception ex)
            {
                ErrorUtil eutil = new ErrorUtil();
                eutil.LogException(_cutil.UserID, "Groups trvGroups_AfterSelect", "", ex);
            }
        }

        private void btnRollback_Click(object sender, EventArgs e)
        {

        }

        private void btnNew_Click(object sender, EventArgs e)
        {

        }

        private void btnSave_Click(object sender, EventArgs e)
        {

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {

        }

    }

    /// <summary>
    /// 
    /// </summary>
    public class GroupTreeNode
    {
        private string _groupname = "";
        private string _gid = "";

        public GroupTreeNode()
        {

        }

        public string GroupName
        {
            get { return _groupname; }
            set { _groupname = value; }
        }

        public string GID
        {
            get { return _gid; }
            set { _gid = value; }
        }
    }
}
